#include "authdatascop.h"
#include "authuser.h"
#include "rolemanager.h"
#include "router/systemManager/roleManager/editroledlg.h"
#include <QMouseEvent>

RoleManager::RoleManager(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_roleManager_hideSearch->setIcon(pix);
    ui->btn_roleManager_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_roleManager_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_roleManager_refresh->setIcon(freshPix.scaled(25,25));
    ui->lineEdit_roleManager_gotoPage->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*")));

    init();

    //隐藏搜索
    connect(ui->btn_roleManager_hideSearch,&QPushButton::clicked,this,[=](){
        ui->widget_40->setHidden(!ui->widget_40->isHidden());
    });
    //下一页
    connect(ui->btn_roleManager_next,&QPushButton::clicked,this,[=](){
        ui->btn_roleManager_next->setEnabled(0);
        currentPage ++;
        getList();
        initTableWidget();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_roleManager_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_roleManager_pervious->setEnabled(0);
        currentPage --;
        getList();
        initTableWidget();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_roleManager_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_roleManager_gotoPage->text().toInt();
        ui->lineEdit_roleManager_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_roleManager_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_roleManager_gotoPage->setStyleSheet("");
        currentPage = page;
        getList();
        initTableWidget();
        initPageInfo();
    });
    //每页大小
    connect(ui->comboBox_roleManager_pageItem,SIGNAL(currentIndexChanged(int)),this,SLOT(pageSizeChanged(int)));
    //重置
    connect(ui->btn_roleManager_reset,&QPushButton::clicked,this,[=](){
        ui->btn_roleManager_reset->setEnabled(0);
        init();
        ui->btn_roleManager_reset->setEnabled(1);
    });
    //搜索
    connect(ui->btn_roleManager_search,&QPushButton::clicked,this,[=](){
        getList();
        initTableWidget();
        initPageInfo();
    });
    //刷新
    connect(ui->btn_roleManager_refresh,&QPushButton::clicked,this,[=](){
        getList();
        initTableWidget();
        initPageInfo();
    });
    //增加
    connect(ui->btn_roleManager_add,&QPushButton::clicked,this,[=](){
        EditRoleDlg e("0",dictList);
        connect(&e,&EditRoleDlg::success,this,[=](){
            getList();
            initTableWidget();
            initPageInfo();
        });
        e.exec();
    });
    //修改
    connect(ui->btn_roleManager_modify,&QPushButton::clicked,this,[=](){
        int index = ui->tableWidget_roleManager->currentRow();
        if(index < 0) return;
        QString id = ui->tableWidget_roleManager->item(index,0)->text();
        EditRoleDlg e(id,dictList);
        connect(&e,&EditRoleDlg::success,this,[=](){
            getList();
            initTableWidget();
            initPageInfo();
        });
        e.exec();
    });
    //批量删除
    connect(ui->btn_roleManager_delete,SIGNAL(clicked()),this,SLOT(deleteByIds()));
    //导出
    connect(ui->btn_roleManager_export,&QPushButton::clicked,this,[=](){
        utils.exportExcel(ui->tableWidget_roleManager,"角色管理表格");
    });
}

bool RoleManager::eventFilter(QObject *obj, QEvent *event)
{
    //mouse button pressed
    if (event->type() == QEvent::MouseButtonPress){
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if(mouseEvent->button() == Qt::LeftButton){
            return true;
        }else{
            return false;
        }
    }else if(event->type() == QEvent::Enter){

        return true;
    }else if(event->type() == QEvent::Leave){
        if(obj == moreDlg){
            moreDlg->close();
        }
        return true;
    }else if(event->type() == QEvent::ActivationChange){
        if(QApplication::activeWindow() != moreDlg){
             moreDlg->close();
        }
        return true;
    }else{
        return QObject::eventFilter(obj, event);
    }
}

void RoleManager::init()
{
    getDict();
    initSearchArea();
    pageSize = 10;
    total = 0;
    currentPage = 1;
    getList();
    initTableWidget();
    initPageInfo();
}

void RoleManager::getList()
{
    roleList.clear();
    QByteArray *data = roleManagerApi.list(currentPage,pageSize,
                     ui->lineEdit_roleManager_roleName->text(),
                     ui->lineEdit_roleManager_roleName->text(),
                     ui->comboBox_roleManager_status->currentData().value<QString>(),
                     ui->dateEdit_roleManager_startTime->text(),
                     ui->dateEdit_roleManager_endTime->text());
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    total = obj.value("total").toInt();
    QJsonArray rows = obj.value("rows").toArray();
    for(int i = 0;i< rows.size();i++){
        Role role = Role::toRole(rows.at(i).toObject());
        roleList.append(role);
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_roleManager_count->setText("共"+QString::number(total)+"条");
}

void RoleManager::getDict()
{
    dictList.clear();
    QByteArray *data = roleManagerApi.sys_normal_disable();
    if(data == nullptr){
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray rows = obj.value("data").toArray();
    for(int i = 0;i< rows.size();i++){
        DictData d = DictData::toDictData(rows.at(i).toObject());
        dictList.append(d);
    }
    delete data;
}

void RoleManager::initTableWidget()
{
    ui->tableWidget_roleManager->setSortingEnabled(0);
    ui->tableWidget_roleManager->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_roleManager->clear();
    QStringList columnHeader;
    columnHeader << "角色编号" << "角色名称" << "权限字符" << "显示顺序" << "状态" << "创建时间" << "操作";
    ui->tableWidget_roleManager->setColumnCount(columnHeader.size());
    ui->tableWidget_roleManager->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget_roleManager->setRowCount(roleList.size());
    ui->tableWidget_roleManager->setColumnWidth(5,150);
    ui->tableWidget_roleManager->setColumnWidth(6,240);
    for(int i = 0;i< roleList.size();i++){
        QString roleId = QString::number(roleList.at(i).roleId);
        ui->tableWidget_roleManager->setItem(i,0,new QTableWidgetItem(roleId));
        ui->tableWidget_roleManager->setItem(i,1,new QTableWidgetItem(roleList.at(i).roleName));
        ui->tableWidget_roleManager->setItem(i,2,new QTableWidgetItem(roleList.at(i).roleKey));
        ui->tableWidget_roleManager->setItem(i,3,new QTableWidgetItem(QString::number(roleList.at(i).roleSort)));
        QCheckBox *box = new QCheckBox();
        box->setCheckState(roleList.at(i).status == "0" ? Qt::Checked : Qt::Unchecked);
        QWidget *widget = new QWidget();
        QHBoxLayout *layout = new QHBoxLayout();
        layout->addWidget(box);
        layout->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        widget->setLayout(layout);
        ui->tableWidget_roleManager->setCellWidget(i,4,widget);
        connect(box,&QCheckBox::clicked,this,[=](){
            QString param = box->checkState() == Qt::Checked ? "启用" : "禁用";
            int flag = QMessageBox::question(0,"提示","确定要【" + param + "】【" + roleList.at(i).roleName +"】角色吗?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                QByteArray *bytes =  roleManagerApi.changeStatus(QString::number(roleList.at(i).roleId),
                            roleList.at(i).status == "0" ? "1" : "0");
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                QJsonObject data = obj.value("data").toObject();
                if(obj.value("code") == 200){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                }
            }else{
                box->setChecked(!box->isChecked());
            }
        });
        ui->tableWidget_roleManager->setItem(i,5,new QTableWidgetItem(roleList.at(i).createTime));
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnUpdate = new QPushButton;
        QPushButton *btnDelete = new QPushButton;
        QPushButton *btnMore = new QPushButton;
        connect(btnDelete,&QPushButton::clicked,this,[=](){
            int flag  = QMessageBox::question(0,"提示","确定删除该项吗?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                if(flag == QMessageBox::No) return;
                QByteArray *bytes = roleManagerApi.deleteItems(roleId);
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                if(200 == obj.value("code").toInt()){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    getList();
                    initTableWidget();
                    initPageInfo();
                }
            }
        });
        connect(btnUpdate,&QPushButton::clicked,this,[=](){;
            EditRoleDlg e(roleId,dictList);
            connect(&e,&EditRoleDlg::success,this,[=](){
                getList();
                initTableWidget();
                initPageInfo();
            });
            e.exec();
        });
        connect(btnMore,&QPushButton::clicked,this,[=](){;
            moreDlg = new QDialog;
            moreDlg->installEventFilter(this);
            QVBoxLayout *l = new QVBoxLayout(moreDlg);
            moreDlg->setWindowFlag(Qt::FramelessWindowHint);
            QPushButton *dataScop = new QPushButton;
            dataScop->setIcon(QIcon(":/svg/res/svg/select.svg"));
            QPushButton *authUser = new QPushButton;
            authUser->setIcon(QIcon(":/svg/res/svg/people.svg"));
            dataScop->setText("数据权限");
            authUser->setText("分配用户");
            l->addWidget(dataScop);
            l->addWidget(authUser);
            moreDlg->move(btnMore->mapToGlobal(QPoint(0,0)).x(),
                          btnMore->mapToGlobal(QPoint(0,0)).y() + 25);
            moreDlg->show();
            connect(dataScop,&QPushButton::clicked,this,[=](){
                moreDlg->close();
                AuthDataScop a(roleId);
                a.exec();
            });
            connect(authUser,&QPushButton::clicked,this,[=](){
                moreDlg->close();
                AuthUser *a = new AuthUser(roleId);
                a->setAttribute(Qt::WA_DeleteOnClose);
                a->exec();
            });
        });
        btnDelete->setText("🗑删除");
        btnUpdate->setText("🖍修改");
        btnMore->setText("》更多");
        btnUpdate->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(231, 250, 240);color: black;}QPushButton:hover {background-color: rgb(19, 206, 102);}QPushButton:pressed {background-color: rgb(19, 150, 102);}");
        btnDelete->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
        btnMore->setStyleSheet  ("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(255, 237, 237);color: black;}QPushButton:hover {background-color: rgb(255, 73, 73);}QPushButton:pressed {background-color: rgb(200, 73, 73);}");
        tmp_layout->addWidget(btnUpdate);
        tmp_layout->addWidget(btnDelete);
        tmp_layout->addWidget(btnMore);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        if(roleId != "1"){
            ui->tableWidget_roleManager->setCellWidget(i,6,tmp_widget);
        }
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_roleManager->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_roleManager->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_roleManager->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_roleManager->setSortingEnabled(1);
}

void RoleManager::initSearchArea()
{
    ui->lineEdit_roleManager_roleName->clear();
    ui->lineEdit_roleManager_roleKey->clear();
    ui->comboBox_roleManager_status->clear();
    ui->comboBox_roleManager_status->addItem("");
    for(int i = 0;i< dictList.size();i++){
        ui->comboBox_roleManager_status->addItem(dictList.at(i).dictLabel,dictList.at(i).dictValue);
    }
    ui->dateEdit_roleManager_startTime->setDate(QDate(2000,1,1));
    ui->dateEdit_roleManager_endTime->setDate(QDate(2000,1,1));
}

void RoleManager::initPageInfo()
{
    if(currentPage == 1){
        ui->btn_roleManager_pervious->setEnabled(0);
    }else{
        ui->btn_roleManager_pervious->setEnabled(1);
    }
    ui->label_roleManager_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_roleManager_next->setEnabled(0);
    }else{
        ui->btn_roleManager_next->setEnabled(1);
    }
}

void RoleManager::pageSizeChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTableWidget();
    initPageInfo();
}

void RoleManager::deleteByIds()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_roleManager->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 5;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget_roleManager->row(items.at(i * 5));
        if(i != rowCount - 1){
            ids += ui->tableWidget_roleManager->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget_roleManager->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选用户吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = roleManagerApi.deleteItems(ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTableWidget();
        initPageInfo();
    }
}
